package cn.sfa.controller.manage;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.FormValidate;
import cn.sfa.common.utils.SendMailUtil;
import cn.sfa.common.utils.WebInitBinderContoller;
import cn.sfa.entity.users.Branch;
import cn.sfa.entity.users.SaleUsersLogin;
import cn.sfa.service.login.LoginService;

/**
 * 
* 类名称：UsersController   
* 类描述： 用户管理处理类
* 创建人：LLY   
* 创建时间：2012-2-14   
* 修改人：LLY   
* 修改时间：2012-2-14   
* 修改备注：   
* @version
 */
@Controller
@RequestMapping("manage/backusers/index")
public class BackUsersController extends WebInitBinderContoller{

	Logger log = LoggerFactory.getLogger(BackUsersController.class);
	@Autowired
	LoginService loginService;
	
	//判断是否是管理员
	public boolean isAdmin(HttpServletRequest request)
	{
		SaleUsersLogin saleUser=(SaleUsersLogin)request.getSession().getAttribute("user");
		if(saleUser.getUserType().equals("USERTYPE_3"))
			return true;
		return false;
	}
	@RequestMapping
	public String index(HttpServletRequest request,HttpServletResponse response,ModelMap map){
		return "backusers/adduser";
	}
	
	@RequestMapping("/adduser")
	public String addUser(HttpServletRequest request,HttpServletResponse response,ModelMap map){
		if(isAdmin(request))
		{
			List<Branch> branchs=loginService.getAllBranchs();
			request.setAttribute("branchs", branchs);
		return "backusers/adduser";
		}
		return "backusers/nopri";
	}
	/**
	 * 添加用户
	 * @param saleUser
	 * @param map
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/add")
	public void add(SaleUsersLogin saleUser,ModelMap map,HttpServletRequest request,HttpServletResponse response) throws Exception
	{
		map.put("saleUser", saleUser);
		List<Branch> branchs=loginService.getAllBranchs();
		request.setAttribute("branchs", branchs);
		
		 
		String add="";
		String mail="";
		int count=0;
		saleUser.setUserType("USERTYPE_4");//内勤
		String email=saleUser.getLoginName();
		//表单验证
		if(CommonUtil.isEmpty(saleUser.getLoginName()))
		{
			mail="电子邮件不能为空！";
			count=count+1;
		}
		else if(loginService.isExists(saleUser.getLoginName()))
		{
			mail="此邮箱已经被注册,请更换邮箱!";
			count=count+1;
		}
		
		boolean result=count==0;
		boolean flag=false;
		if(result)
		{
		
		
		//设置SaleUsersLogin用户属性
		
		
			SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
			saleUser.setCreateUid(user.getSaleUsersLoginId());
			saleUser.setCreateDate(new Date());
			saleUser.setUpdateId(user.getSaleUsersLoginId());
			saleUser.setUpdateDate(new Date());
			saleUser.setUserStatus("y");//表示开启用户
			saleUser.setUserKind("");
			saleUser.setIsAnonymous("n");//是否匿名
			
			saleUser.setLastPwdChangeDate(new Date());
			saleUser.setSendMailDate(new Date());
			saleUser.setUserAgentId(user.getSaleUsersLoginId());
			saleUser.setEmail(email+"@hkfs.cn");
			saleUser.setLoginName(email);
			saleUser.setContactMobile("");
			saleUser.setUserPassword("");//因为ＡＤ取不到密码，所以先给出空值，待用户登录时，获取他的密码更新user表
		 
			 
				//添加USER表用户
				flag=loginService.addUser(saleUser);
				if(flag)
				{
					add="新用户已经成功添加！";
					//发送邮件
					SendMailUtil sendMail=new SendMailUtil();
					String content="亲爱的"+email+"\n您好！您可以使用此帐号登录CRM，您的登录密码是您的"+
					email+"@hkfs.cn邮箱登录密码！建议您确认无误后删除本邮件！";
					sendMail.send(email+"@hkfs.cn", content,"CRM提示");
					 
				}else 
				{
					add="新用户添加失败！";
				}
				 
		} 
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");
 
            JSONObject temp = new JSONObject();
            temp.put("msg",add);
            temp.put("flag", flag);
            temp.put("result",result);
            temp.put("mail", mail);
             
            PrintWriter out=response.getWriter();
	        out.print(temp.toString());
			out.flush();
			out.close();
		 
	}
	@RequestMapping("/getusers")
	public String getUers(HttpServletRequest request,HttpServletResponse response,ModelMap map){
		List saleUsers=new ArrayList();	
		String adminid=(String)request.getSession().getAttribute("adminid");
		SaleUsersLogin curUser=(SaleUsersLogin)request.getSession().getAttribute("user");
		saleUsers=loginService.allBackUsers(curUser.getSaleUsersLoginId());
		

		
		List<Object> adUsers=new ArrayList<Object>();
		for(int i=0;i<saleUsers.size();i++)
		{
			Map<String,String> mapTemp = new HashMap<String,String>();
			
			mapTemp = (Map<String,String>)saleUsers.get(i);
			String userType=mapTemp.get("USERTYPE");
		}
		request.setAttribute("users",adUsers);
		return "backusers/getusers";
	}
	
	@RequestMapping("/update")
	public String update(ModelMap map,HttpServletRequest request,HttpServletResponse response)
	{
		String loginName=request.getParameter("loginName");
  
		String email=request.getParameter("email");
		String username=request.getParameter("username");
		String contactMobile=request.getParameter("contactMobile");
		String saleUsersLoginId=request.getParameter("saleUsersLoginId");
		
		SaleUsersLogin curUser=new SaleUsersLogin();
		curUser.setLoginName(loginName);
		curUser.setEmail(email);
		curUser.setUserName(username);
		curUser.setContactMobile(contactMobile);
		curUser.setSaleUsersLoginId(saleUsersLoginId);
		map.put("currentUser", curUser);
		//表单验证
		if(loginName==null || "".equals(loginName))
		{
			map.put("name", "用户名不能为空！");
			return "backusers/updatepwd";
		} else if(username==null || "".equals(username))
		{
			map.put("userName", "用户姓名不能为空！");
			return "backusers/adduser";
		} else if(!FormValidate.isMail(email))
		{
			map.put("mail", "电子邮件格式不正确");
			return "backusers/updatepwd";
		}else if(loginService.existsEmail(saleUsersLoginId, email))
		{
			map.put("mail", "此邮箱已经被注册，请更换其它邮箱");
			return "backusers/updatepwd";
		}else if(contactMobile==null || "".equals(contactMobile))
		{
			
		}else if(!FormValidate.isMobileNumber(contactMobile))
		{
			map.put("contact", "手机号码格式不正确！如：189XXXXXXXX");
			return "backusers/updatepwd";
		}
		SaleUsersLogin saleUser=loginService.getUserByLoginName(loginName);
		if(isAdmin(request) || loginName.equals(saleUser.getLoginName()))
		{

			SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
			 
					saleUser.setUserPassword(saleUser.getUserPassword());
					saleUser.setContactMobile(contactMobile);
					saleUser.setUpdateDate(new Date());
					saleUser.setUpdateId(user.getSaleUsersLoginId());
					saleUser.setEmail(email);
					saleUser.setUserName(username);
					boolean flag=loginService.updateUserInfo(saleUser);
					if(flag)
					{
					map.addAttribute("msg", "修改成功！");
					return this.getUers(request, response, map);
					}
					else
					{
						map.addAttribute("update","修改出错！");
						return "backusers/updatepwd";
					}
			
			}
			return "backusers/nopri";
	}
	
	@RequestMapping("/updatepwd")
	public String updatePwd(HttpServletRequest request,HttpServletResponse response,ModelMap map){
		String loginName=request.getParameter("loginName");
		SaleUsersLogin saleUser=(SaleUsersLogin)request.getSession().getAttribute("user");
		SaleUsersLogin currentUser=null;
		if(isAdmin(request) || saleUser.getLoginName().equals(loginName))
		{
	 
		currentUser=loginService.getUserByLoginName(loginName);
		request.setAttribute("currentUser", currentUser);
		return "backusers/updatepwd";
		}
		 
		return "backusers/nopri";
	}
	
	@RequestMapping("/isallow")
	public void isallow(HttpServletRequest request,HttpServletResponse response,ModelMap map) throws IOException{
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		String userStatus=request.getParameter("userStatus");
		String loginName=request.getParameter("loginName");
		SaleUsersLogin saleUser=loginService.getUserByLoginName(loginName);
		 
		
		if(!user.getUserName().equals(loginName))
		{
		
			if("y".equals(userStatus))
			{
				
				saleUser.setUserStatus("n");
				
			}else
			{
				saleUser.setUserStatus("y");
			}
		
		}
		boolean flag=loginService.updateUser(saleUser);
		response.setContentType("text/json");
		PrintWriter out=response.getWriter();
		 
			JSONObject jo = new JSONObject();
			jo.put("isDel", flag);
			out.print(jo.toString());
			out.flush();
			out.close();
		 
	}
	
	
}
